﻿using DevelopAssistant.Core.ToolBar;
using DevelopAssistant.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DevelopAssistant.Core.ToolBox
{
    public partial class EditDataBaseConnection : ToolBoxBase
    {
        public bool AllObjectLoad = false;

        public string ConnectionId { get; set; }
        public string ConnectionName = String.Empty;
        public string ProviderName = String.Empty;
        public string ConnectionString = String.Empty;

        protected Color foreColor = SystemColors.WindowText;
        protected Color backColor = SystemColors.Control;
        protected Color toolBackColor = SystemColors.Control;

        public string dbserverName = string.Empty;
        public EventHandler Apply { private get; set; }
        public EventHandler Cancle { private get; set; }

        public EditDataBaseConnection()
        {
            InitializeComponent();
            InitializeControls();
        }

        private void InitializeControls()
        {             
            this.panel1.BorderColor = this.XTheme.FormBorderOutterColor;
        }

        public EditDataBaseConnection EditDataBaseConnectiontor(DataBaseServer dbserver, MenuBar menubar)
             
        {
            EditDataBaseConnection _base =new EditSqlServerConnection(dbserver,menubar);

            switch (dbserver.ProviderName)
            {
                case "System.Data.Sql":
                case "System.Data.SQL":
                    _base = new EditSqlServerConnection(dbserver, menubar);
                    break;
                case "System.Data.Sqlite":
                    _base = new EditSqliteServerConnection(dbserver, menubar);
                    break;
                case "System.Data.PostgreSql": 
                    _base = new EditPostgreSqlServerConnection(dbserver, menubar);
                    break;
                case "System.Data.MySql":
                    _base = new EditMySqlServerConnection(dbserver, menubar);
                    break;
                case "System.Data.OleDb":
                    _base = new EditOleDbServerConnection(dbserver, menubar);
                    break;
            }

            return _base;
        }

        protected List<string> GetServersRecords(string dataType)
        {
            List<string> rvl = new List<string>();

            try
            {
                using (var db = NORM.DataBase.DataBaseFactory.Create("default"))
                {
                    //name value
                    string sqlText = "SELECT [name] FROM [T_ServersRecords] ORDER BY [createDate] DESC";
                    using (DataSet ds = db.QueryDataSet(System.Data.CommandType.Text, sqlText, null))
                    {
                        DataTable dt = ds.Tables[0];
                        foreach (DataRow dr in dt.Rows)
                        {
                            rvl.Add(dr["name"] + "");
                        }
                        dt.Dispose();
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return rvl;
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            if (this.Cancle != null)
                this.Cancle(sender, new EventArgs());
            this.DialogResult = DialogResult.No;
        }

        protected void SetBtnApplyEnabled(bool bl)
        {
            this.btnApplyOk.Enabled = bl;
        }

        private void btnApplyOk_Click(object sender, EventArgs e)
        {
            if (this.Apply != null)
                this.Apply(sender, new EventArgs());

            try
            {
                using (var db = NORM.DataBase.DataBaseFactory.Create("default"))
                {
                    db.BeginTransaction();

                    DataBaseServer dbserver = new DataBaseServer(ConnectionString, ProviderName);
                    dbserver.ID = ConnectionId;

                    string connectionName = string.Empty;

                    if (string.IsNullOrEmpty(ConnectionName))
                    {
                        connectionName = dbserver.DataBaseName +
                            "(" + dbserver.Server + "";
                        if (!string.IsNullOrEmpty(dbserver.Port))
                        {
                            connectionName += "," + dbserver.Port + "";
                        }
                        if (!string.IsNullOrEmpty(dbserver.Instance_Name))
                        {
                            connectionName += "\\" + dbserver.Instance_Name;
                        }
                        connectionName += ")";
                    }
                    else
                    {
                        connectionName = ConnectionName;
                    }

                    dbserver.Name = connectionName;

                    //string sqlText = "INSERT INTO [T_ServersRecords] (";
                    //sqlText += " [name],[value],[dataType],[createDate] )";
                    //sqlText += " SELECT";
                    //sqlText += " '" + dbserver.Server + "','" + dbserver.Port + "','" + dbserver.ProviderName + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                    //sqlText += " where not exists (";
                    //sqlText += " select * from [T_ServersRecords] ";
                    //sqlText += " where [name]='" + dbserver.Server + "')";

                    //int val = db.Execute(System.Data.CommandType.Text, sqlText, null);


                    string sqlText = "UPDATE [T_DataBaseServers] SET ";
                    sqlText += " [connectionString]='" + dbserver.ConnectionString + "',[dataBaseType]='" + dbserver.ProviderName + "',[connectionName]='" + dbserver.Name + "' ";
                    sqlText += " where [connectionID]='" + dbserver.ID + "' ";

                    db.Execute(System.Data.CommandType.Text, sqlText, null);

                    db.Commit();

                    //将更改后的名称赋值给dbserverName
                    dbserverName = dbserver.Name;

                }

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            } 
            
        }

        protected virtual void OnThemeChanged(ThemeEventArgs e)
        {
            string themeName = AppSettings.EditorSettings.TSQLEditorTheme;
            switch (themeName)
            {
                case "Default":
                    foreColor = SystemColors.WindowText;
                    backColor = SystemColors.Control;
                    toolBackColor = SystemColors.Control;
                    break;
                case "Black":
                    foreColor = Color.FromArgb(240, 240, 240);
                    backColor = Color.FromArgb(045, 045, 048);
                    toolBackColor = Color.FromArgb(038, 038, 038);
                    break;
            }            
            XBackgroundColor = backColor;
            panel1.ForeColor = foreColor;
            panel1.BackColor = backColor;
            btnApplyOk.ForeColor = foreColor;
            btnApplyOk.BackColor = toolBackColor;
            btnCancle.ForeColor = foreColor;
            btnCancle.BackColor = toolBackColor;
            e.themeName = themeName;
        }

    }
}
